package org.rkuk.kasutil.media 
{
	/**
	 * ...
	 * @author rkuk
	 */
	internal class StopState extends MediaState 
	{
		private var isReseting:Boolean;
		private var isPlaying:Boolean;
		
		public function StopState(media:MediaProxy)
		{
			super(media);
			isReseting = isPlaying = false;
		}
		
		/**
		 * @inheritDoc
		 */
		override public function get description():String 
		{
			return MediaSourceEvent.STOP;
		}
		
		/**
		 * @inheritDoc
		 */
		override public function dispose():void 
		{
			if(media.hasEventListener(MediaStreamStatusEvent.STATUS_PLAY))
				media.removeEventListener(MediaStreamStatusEvent.STATUS_PLAY, onMediaPlay);
			if(media.hasEventListener(MediaStreamStatusEvent.STATUS_STOP))
				media.removeEventListener(MediaStreamStatusEvent.STATUS_STOP, onMediaReset);
				
			super.dispose();
		}
		
		/**
		 * 征听MediaProxy发出的Play事件，切换状态并发出MediaSourceEvent
		 * @param	e	MediaProxy发出的Play事件
		 */
		private function onMediaPlay(e:MediaStreamStatusEvent):void 
		{
			var media:MediaProxy = this.media;
			dispose();
			
			media.state = new PlayState(media);
		}
		
		/**
		 * @inheritDoc
		 */
		override public function start(...rest):void 
		{
			if (!isPlaying && !isReseting)
			{
				isPlaying = true;
				media.addEventListener(MediaStreamStatusEvent.STATUS_PLAY, onMediaPlay);
				media.start.apply(media, rest);
			}
		}
		
		/**
		 * @inheritDoc
		 */
		override public function reset():void 
		{
			if (!isReseting)
			{
				isReseting = true;
				if (isPlaying)
				{
					//确认在播放启动之前就停止，是否真的会收到STATUS_STOP?
					media.removeEventListener(MediaStreamStatusEvent.STATUS_PLAY, onMediaPlay);
					media.addEventListener(MediaStreamStatusEvent.STATUS_STOP, onMediaReset);
					media.stop();
				}
				else
					onMediaReset();
			}
		}
		
		private function onMediaReset(e:MediaStreamStatusEvent=null):void 
		{
			var media:MediaProxy = this.media;
			dispose();
			
			media.state = new ResetState(media);
		}
	}
}